// 用户状态管理
import { getUserInfo } from '@/api/user.js'

const state = {
  token: uni.getStorageSync('token') || '',
  userInfo: uni.getStorageSync('userInfo') || {},
  roles: [],
  permissions: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    uni.setStorageSync('token', token)
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
    uni.setStorageSync('userInfo', userInfo)
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  CLEAR_USER: (state) => {
    state.token = ''
    state.userInfo = {}
    state.roles = []
    state.permissions = []
    uni.removeStorageSync('token')
    uni.removeStorageSync('userInfo')
  }
}

const actions = {
  // 获取用户信息
  async fetchUserInfo({ commit }) {
    try {
      const response = await getUserInfo()
      if (response && response.code === 200) {
        const { user, roles, permissions } = response
        
        // 确保用户信息包含必要的字段
        const userInfo = {
          userId: user.userId || user.id || user.userId,
          nickName: user.nickName || user.userName,
          userName: user.userName,
          avatar: user.avatar,
          email: user.email,
          phonenumber: user.phonenumber,
          sex: user.sex,
          remark: user.remark
        }
        
        commit('SET_USER_INFO', userInfo)
        commit('SET_ROLES', roles || [])
        commit('SET_PERMISSIONS', permissions || [])
        
        // 同时保存到本地存储
        uni.setStorageSync('userInfo', userInfo)
        
        return response
      } else {
        throw new Error(response?.msg || '获取用户信息失败')
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  },

  // 设置token
  setToken({ commit }, token) {
    commit('SET_TOKEN', token)
  },

  // 清除用户信息
  clearUser({ commit }) {
    commit('CLEAR_USER')
  }
}

const getters = {
  token: state => state.token,
  userInfo: state => state.userInfo,
  roles: state => state.roles,
  permissions: state => state.permissions,
  isLoggedIn: state => !!state.token
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
